#-*- coding:utf-8 -*-
from atexit import register
from MyTrans import myTrans
import re
import os
import xlsxwriter
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class Execute():
    def __init__(self,step=None,host=None,port=None,username=None,password=None,nmonPath=None,command=None,local_nmon_path=None,local_result_path=None,analysis_path=None,root=None):
        self.step=step
        self.ip=host
        self.port=port
        self.uname=username
        self.passwd=password
        self.nmonpath=nmonPath
        self.up_command=command.split('-F ')
        self.up_command=self.up_command[0]+'-F '+self.ip+'_'+self.up_command[1]
        self.cmd=command
        self.local_nmon_path=local_nmon_path
        self.local_result_path=local_result_path
        self.analysis_path=analysis_path
        self.root=root
        self._connect()
    def _connect(self):
        try:
            self.server=myTrans(ip=self.ip,port=self.port,uname=self.uname,passwd=self.passwd)
        except Exception as e:
            self.root.set_res(self.ip+'\n')
            self.root.set_res(e)
            self.root.set_res('\n')
            return 0
        eval('self._%s()'%(self.step))
    def _upNmon(self):
        self.server.create_chan()
        command=['cd %s\n' % (self.nmonpath),'%s\n'%(self.up_command)]
        self.server.exec_cmd(command)
        # self.root.set_res(self.server.result)
        a=['No such','Not Found','not found','not allow','permission denied','ERROR']
        for i in a:
            if i in self.server.result:
                self.root.set_res(self.ip+'\nnmon启动失败！\n'+self.server.result+'\n')
                return 0
        command=['%s "nmon"\n' % (self.server.ps)]
        self.server.exec_cmd(command)
        self.root.set_res(self.ip+'\nnmon启动成功！\n'+self.server.result+'\n')
        self.server.exit()
    def _killNmon(self):
        self.server.create_chan()
        self.server.exec_cmd(['%s "nmon"\n'%(self.server.ps)])
        nmon_ps=re.search(r'\w+\s*(\d+)\s+1\s',self.server.result)
        if nmon_ps:
            nmon_ps=nmon_ps.group(1)
            command=['%s "nmon"\n'%(self.server.ps),'kill -9 %s\n' % (nmon_ps),'%s "nmon"\n'%(self.server.ps)]
            self.server.exec_cmd(command)
            self.root.set_res(self.ip+'\nkill nmon成功！\n'+self.server.result+'\n')
        else:
            self.root.set_res(self.ip+'\n没有找到nmon进程!\n'+self.server.result+'\n')
        self.server.exit()
    def _downloadResult(self):
        self.server.create_chan()
        if not os.path.exists(self.local_result_path):
            os.mkdir(self.local_result_path)
        try:
            command=['find %s -name "*.nmon"\n' % (self.nmonpath),]
            self.server.exec_cmd(command)
            result=re.split(r'\r\n',self.server.result)
            s=0
            for i in result:
                result1=re.search(r'(/.+/([^\*]+\.nmon))', i)
                if result1:
                    local_result_path=os.path.join(self.local_result_path,result1.group(2))
                    self.server.donwload(result1.group(1),'%s' % (local_result_path))
                    self.root.set_res(self.ip+'\n'+result1.group(2)+'\n下载完成！\n\n')
                    s+=1
            if not s:
                self.root.set_res(self.ip+'\n没有找到监控结果文件！\n'+self.server.result+'\n')
        except Exception as e:
            self.root.set_res(self.ip+'\n')
            self.root.set_res(e)
            self.root.set_res('\n')
        self.server.exit()
    def _DeleteResult(self):
        self.server.create_chan()
        if self.server.sysname=='Linux':
            command=['find %s*.nmon -delete\n' % (self.nmonpath)]
        else:
            command=['find %s*.nmon | xargs rm\n' % (self.nmonpath)]
        self.server.exec_cmd(command)
        if 'No such file' in self.server.result or 'Not Found' in self.server.result or 'is not' in self.server.result:
            self.root.set_res(self.ip+'\n没有找到监控结果文件！\n'+self.server.result+'\n')
        else:
            self.root.set_res(self.ip+'\n监控结果删除成功！\n'+self.server.result+'\n')
        self.server.exit()
    def _upload_nmon(self):
        self.server.create_chan()
        file_name=self.local_nmon_path.split('\\')[-1]
        self.server.upload(self.local_nmon_path,'%s%s' % (self.nmonpath,file_name))
        self.server.create_chan()
        command=['chmod 755 %s%s\n' % (self.nmonpath,file_name)]
        self.server.exec_cmd(command)
        self.root.set_res(self.ip+'\n上传nmon成功!\n'+self.server.result+'\n')
        self.server.exit()




class parseResult():
    def __init__(self,local_result_path,analysis_path,root):
        self.local_result_path=local_result_path.decode('utf8')
        self.analysis_path=analysis_path.decode('utf8')
        self.root=root
        self._execute()
    def _execute(self):
        if os.path.exists(self.analysis_path):
            if os.path.isfile(self.analysis_path):
                pass
            else:
                self.analysis_path = os.path.join(self.analysis_path, 'ana_result.xlsx')
        else:
            name=self.analysis_path.split('\\')[-1]
            if '.xls' in name:
                paths=self.analysis_path.split(name)[0]
                if not os.path.exists(paths):
                    os.makedirs(paths.strip('\\'))
            else:
                if not os.path.exists(self.analysis_path):
                    os.makedirs(self.analysis_path)
        filename_list=[]
        for i in os.listdir(self.local_result_path):
            if i.endswith('.nmon'):
                filename_list.append(i)
            else:
                continue
        self.workbook=xlsxwriter.Workbook(self.analysis_path)
        sheet = self.workbook.add_worksheet('summary')
        sheet.write(0, 0, 'IP')
        sheet.write(0, 1, 'CPU(%)')
        sheet.write(0, 2, 'IO(%)')
        sheet.write(0, 3, 'MEM(%)')
        j=0
        for i in range(len(filename_list)):
            ip = re.search('\d+\.\d+\.\d+\.\d+', filename_list[i])
            sheetname=ip.group() if ip else filename_list[i]
            #合并下载结果保存路径和监控结果名称
            path = os.path.join(self.local_result_path, filename_list[i])
            #调用read_nmon_result解析path中指定的结果文件，
            result = read_nmon_result(path)
            #将平均结果保存到'summary'sheet页中
            j+=1
            sheet.write(j, 0, sheetname)
            sheet.write(j, 1, result.avg_cpu)
            sheet.write(j, 2, result.ave_disk)
            sheet.write(j, 3, result.ave_mem)

            #以ip作为sheet页名称新建sheet页，并写表头，填写数据
            sheet1=self.workbook.add_worksheet(name=sheetname)
            sheet1.write(0,0,'Time')
            sheet1.write(0, 1, 'CPU(%)')
            sheet1.write(0, 2, 'IO(%)')
            sheet1.write(0, 3, 'MEM(%)')
            sheet1.write_column("A2",result.times)
            sheet1.write_column("B2", result.cpu)
            sheet1.write_column("C2", result.diskbusy)
            sheet1.write_column("D2", result.mem)
            #获取数据行数
            rows=len(result.times)
            #创建图表
            chart1=self.workbook.add_chart({'type':'line'})
            color=['blue','orange','gray']
            for i in range(1,4):
                chart1.add_series({
                    'name':[sheetname,0,i],
                    'categories':[sheetname,1,0,rows+1,0],
                    'values':[sheetname,1,i,rows+1,i],
                    'line':{'color':color[i-1],'width':1.75},
                })
            chart1.set_title({'name':sheetname})
            chart1.set_y_axis({'name':'百分比（%）','max':'100','min':'0'})
            chart1.height=600
            chart1.width=1000
            chart1.set_style(14)
            sheet1.insert_chart('G11',chart1)
        try:
            self.workbook.close()
        except IOError:
            self.root.set_res('%s已打开，请关闭重试！\n'%(self.analysis_path))
        except Exception as e:
            self.root.set_res(e)
            self.root.set_res('\n')
        # print '监控结果分析完成，保存在%s'%(self.analysis_path)
        self.root.set_res('监控结果分析完成，保存在%s'%(self.analysis_path))
class read_nmon_result():
    def __init__(self,filepaht):
        self.filepaht=filepaht
        self._read_file()
    def _read_file(self):
        with open(self.filepaht,'r') as f:
            self.lines = f.readlines()
            for i in self.lines:
                if 'build,AIX' in i:
                    self.platform = 'AIX'
                elif 'OS,Linux' in i:
                    self.platform = 'Linux'
            self._get_times()
            self._getCpu()
            self._getDisk()
            self._getMem()
    def _get_times(self):
        self.times=[]
        for i in self.lines:
            i=i.split(',')
            if i[0]=='ZZZZ':
                self.times.append(i[2])
    def _getCpu(self):
        self.cpu=[]
        for i in self.lines:
            i=i.split(',')
            if i[0]=='CPU_ALL' and 'CPU Total' not in i[1]:
                self.cpu.append(100-float(i[5]))
        self.avg_cpu=round(sum(self.cpu)/len(self.cpu),3)
    def _getDisk(self):
        self.diskbusy=[]
        for i in self.lines:
            i=i.split(',')
            if i[0]=='DISKBUSY' and 'Disk %Busy' not in i[1]:
                self.diskbusy.append(max(map(float,i[2:])))
        self.ave_disk=round(sum(self.diskbusy)/len(self.diskbusy),2)
    def _getMem(self):
        self.mem = []
        if self.platform=='Linux':
            for i in self.lines:
                i=i.split(',')
                if i[0]=='MEM' and 'Memory MB' not in i[1]:
                    self.mem.append(round((float(i[2])-float(i[6])-float(i[11])-float(i[14]))/float(i[2]),4)*100)
            self.ave_mem=round(sum(self.mem)/len(self.mem),2)
        elif self.platform=='AIX':
            realfree=[]
            numperm=[]
            for i in self.lines:
                i = i.split(',')
                if i[0]=='MEM':
                    realfree.append((i[2]))
                if i[0]=='MEMUSE':
                    numperm.append((i[2]))
            realfree.pop(0)
            numperm.pop(0)
            realfree=map(float,realfree)
            numperm=map(float,numperm)
            for i in range(len(realfree)):
                self.mem.append(round(100-realfree[i]-numperm[i],2))
            self.ave_mem=round(sum(self.mem)/len(self.mem),2)